package batch.sqltodb;

import java.io.*;
import java.sql.*;
import java.util.List;
import batch.common.db.*;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Category;
import org.apache.log4j.Logger;

public class SqlToDB 
{
    private Connection    conn;
    private QueryRunner   qRunner;
    private Logger log;

    public SqlToDB()
    {
        log = Logger.getLogger("sqltodb"); 
    }

    public void execMigration(String SITE)
    {
        int nUptCount = 0;
        String strChar = "";
        if(SITE.equals("RUS"))
            strChar = "UTF-8";
        else
            strChar = "UTF-8";
        log.info("[START]");
        try
        {
        	qRunner = new QueryRunner();
            conn = ConnectionManager.getConnection();
            conn.setAutoCommit(false);
            List lMessages = FileUtils.readLines(new File("/home01/sfc/batch/sqltodb/scr/" + SITE), strChar);
            for(int i = 0; i < lMessages.size(); i++)
            {
            	           	
                String temp = (String)lMessages.get(i);
                nUptCount = qRunner.update(conn, temp);
                log.info(""+i+"=> \n"+temp+"\n[result="+nUptCount+"]");
            }

            conn.commit();
            conn.setAutoCommit(true);
        }
        catch(FileNotFoundException fnfe)
        {
            log.error("", fnfe);
        }
        catch(IOException ioe)
        {
            log.error("", ioe);
        }
        catch(Exception ex)
        {
            if(conn != null)
                try
                {
                    conn.rollback();
                }
                catch(Exception ex1)
                {
                    log.error("", ex1);
                }
            log.error("", ex);
        }
        finally
        {
            log.debug("[END]");
 
            if(conn != null)
                try
                {
                    conn.close();
                }
                catch(Exception ce)
                {
                    log.error("", ce);
                }
            
        }
    }

    public static void main(String args[])
    {
        SqlToDB mgr = new SqlToDB();
        mgr.execMigration(args[0]);
    }
}
